package com.qu.waibao.my.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.qu.waibao.AppConfig;
import com.qu.waibao.R;
import com.qu.waibao.baidu.LocationUtils;
import com.qu.waibao.baidu.MapActivity;
import com.qu.waibao.base.BaseActivity;
import com.qu.waibao.interf.XnetCallBack;
import com.qu.waibao.network.ActionUtil;
import com.qu.waibao.network.HttpModeBase;
import com.qu.waibao.network.NetManager;
import com.qu.waibao.utils.ImageLoader;
import com.qu.waibao.utils.LogUtil;
import com.qu.waibao.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import info.wangchen.simplehud.SimpleHUD;

public class PersonInfoActivity extends BaseActivity implements View.OnClickListener{
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_sure)
    TextView tv_sure;
    @BindView(R.id.iv_publish)
    ImageView iv_publish;
    @BindView(R.id.iv_photo)
    CircleImageView iv_photo;
    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.et_address)
    EditText et_address;
    @BindView(R.id.tv_location)
    TextView tv_location;
    private HttpModeBase httpModeBase;
    private String uploadImage = "";
    private String province = "";
    private String city = "";
    private String area = "";
    private String longitude = "";
    private String latitude = "";
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case HttpModeBase.HTTP_SUCCESS:
                    String result = (String) msg.obj;
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if(jsonObject.optInt("status") == 1){
                            uploadImage = jsonObject.optString("src");
                            ImageLoader.loadImage(getImageLoader(),iv_photo,NetManager.getFullUrl(uploadImage),R.drawable.grxx_touxiang,
                                    R.drawable.grxx_touxiang);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case HttpModeBase.HTTP_ERROR:
                    SimpleHUD.dismiss();
                    break;
            }
        }
    };
    @Override
    protected int getContentView() {
        return R.layout.activity_person_info;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        tv_title.setText("个人信息");
        iv_publish.setVisibility(View.GONE);
        tv_sure.setVisibility(View.VISIBLE);
        httpModeBase = new HttpModeBase(handler,this);
        if(LocationUtils.Mylocation != null){
            province = LocationUtils.Mylocation.getProvince();
            city = LocationUtils.Mylocation.getCity();
            area = LocationUtils.Mylocation.getDistrict();
        }
    }

    @Override
    protected void initData() {
        super.initData();
        getUserInfo();
    }
    @OnClick({R.id.ll_back,R.id.tv_sure,R.id.iv_photo,R.id.rl_ding})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_back:
                finish();
                break;
            case R.id.rl_ding:
                startActivityForResult(new Intent(this, MapActivity.class),0);
                break;
            case R.id.tv_sure:
                String name = et_name.getText().toString();
                String phone = et_phone.getText().toString();
                String address = et_address.getText().toString();
                if(TextUtils.isEmpty(name)){
                    ToastUtil.show(this,"请输入您的真实姓名");
                    return;
                }else if(TextUtils.isEmpty(phone)){
                    ToastUtil.show(this,"请输入您的电话");
                    return;
                }else if(TextUtils.isEmpty(address)){
                    ToastUtil.show(this,"请选择您的地址");
                    return;
                }
                userInfoSet(name,phone,address);
                break;
            case R.id.iv_photo: //上传头像
                openPhotos();
                break;

        }
    }

    public void getUserInfo(){
        Map<String,String> map = new HashMap<>();
        map.put("action", ActionUtil.user_info_get);
        map.put("userid", AppConfig.getString("userid"));
        NetManager.getInstance().request(this, map, true, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String photo = jsonObject.optString("photo");
                    if(!TextUtils.isEmpty(jsonObject.optString("photo"))){
                        ImageLoader.loadImage(getImageLoader(),iv_photo,NetManager.getFullUrl(photo),R.drawable.grxx_touxiang,
                                R.drawable.grxx_touxiang);
                    }
                    uploadImage = photo;
                    et_name.setText(jsonObject.optString("name"));
                    et_phone.setText(jsonObject.optString("phone"));
                    et_address.setText(jsonObject.optString("address"));
                    tv_location.setText(jsonObject.optString("province")+jsonObject.optString("city")+
                            jsonObject.optString("area"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    public void ImageSaveSet(String path){
        httpModeBase.xutilsPost(NetManager.BaseUrl,NetManager.image_save_set(),path,true);
    }
    public void userInfoSet(String name,String phone,String address){
        Map<String,String> map = new HashMap<>();
        map.put("action",ActionUtil.user_info_set);
        map.put("userid",AppConfig.getString("userid"));
        map.put("name",name);
        map.put("province",province);
        map.put("city",city);
        map.put("area",area);
        map.put("address",address);
        map.put("longitude",longitude);
        map.put("latitude",latitude);
        map.put("linktel",phone);
        map.put("photo",uploadImage);
        NetManager.getInstance().request(this, map, true, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
               ToastUtil.show(PersonInfoActivity.this,msg);
               finish();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    /**
     * 打开相册
     */
    public void openPhotos() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(1)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .enableCrop(true)// 是否裁剪
                .openClickSound(true)
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .isGif(false)// 是否显示gif图片
                .compress(true)// 是否压缩 true or false
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data != null){
            switch (requestCode){
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> list = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia = list.get(0);
                    String path = "";
                    if(localMedia.isCompressed()){
                        path = localMedia.getCompressPath();
                    }else {
                        path = localMedia.getPath();
                    }
                    ImageSaveSet(path);
                    break;
                case 0:
                    if(data != null){
                       latitude = String.valueOf(data.getDoubleExtra("latitude",0));
                       longitude = String.valueOf(data.getDoubleExtra("longitude",0));
                       String address = data.getStringExtra("address");
                       et_address.setText(address);
                       if(LocationUtils.Mylocation != null){
                           tv_location.setText(LocationUtils.Mylocation.getProvince()
                                   +LocationUtils.Mylocation.getCity()+LocationUtils.Mylocation.getDistrict());
                       }
                    }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
                == PackageManager.PERMISSION_GRANTED){
            PictureFileUtils.deleteCacheDirFile(this);
        }
    }
}
